import asyncio
import json
import random

from langchain_core.tools import tool
from langchain_mcp_adapters.client import MultiServerMCPClient

from app.core.logging import logger

_all_tools = None
async def get_all_tools():
    """
    统一的工具准备函数，避免重复初始化MCP客户端

    Returns:
        list: 包含所有可用工具的列表
    """
    global _all_tools

    # 如果已经初始化过，直接返回
    if _all_tools is not None:
        return _all_tools

    # 创建MCP客户端以获取搜索工具
    try:
        client = MultiServerMCPClient(
            {
                "gaode": {
                    "url": "https://dashscope.aliyuncs.com/api/v1/mcps/amap-maps/sse",
                    "transport": "sse",
                    "headers": {
                        "Authorization": "sk-3815bc7f8901434e97ed70757d61e957"
                    }

                }
            }
        )
        # 获取MCP工具
        mcp_tools = await client.get_tools()
        _all_tools = mcp_tools
        logger.info(f"工具初始化成功，可用工具: {[tool.name for tool in _all_tools]}")

    except Exception as e:
        logger.warning(f"⚠️ MCP工具初始化失败: {e}")
        # 如果MCP工具失败，只使用邮件工具
        _all_tools = [get_weather]
        logger.info(f"使用备用工具: {[tool.name for tool in _all_tools]}")

    return _all_tools


async def test_mcp_connection():
    """测试MCP连接的主函数"""
    print("开始测试MCP连接...")

    try:
        # 获取所有工具
        tools = await get_all_tools()
        print(f"成功获取工具列表: {[tool.name for tool in tools]}")

        # 尝试调用每个工具
        for tool in tools:
            print(f"\n测试工具: {tool.name}")
            try:
                if tool.name == "maps_weather":
                    # 天气工具测试
                    result = await tool.ainvoke({"city": "太仓"})
                    print(f"  工具调用成功: {result}")
                else:
                    print(f"  未知工具类型，跳过调用")
            except Exception as e:
                print(f"  工具调用失败: {e}")

    except Exception as e:
        print(f"MCP连接测试失败: {e}")
        import traceback
        traceback.print_exc()
@tool
def get_weather(location: str):
    """
    使用该工具获取指定位置的天气信息

    Args:
        location: 地点名称，如"北京"、"上海"等

    Returns:
        str: 天气信息描述
    """

    # 模拟天气数据
    weather_conditions = ["晴朗", "多云", "阴天", "小雨", "大雨", "雷阵雨", "小雪", "大雪"]
    temp = round(random.uniform(5, 35), 1)
    humidity = random.randint(30, 95)
    wind_speed = round(random.uniform(0, 10), 1)
    wind_direction = random.choice(["东", "南", "西", "北", "东北", "西北", "东南", "西南"])

    # 构建JSON格式的天气数据
    weather_data = {
        "location": location,
        "condition": random.choice(weather_conditions),
        "temperature": temp,
        "humidity": humidity,
        "wind": {
            "speed": wind_speed,
            "direction": wind_direction
        },
        "updated_at": "2023-06-15 14:30"
    }

    result = json.dumps(weather_data, ensure_ascii=False)
    return result
if __name__ == "__main__":
    asyncio.run(test_mcp_connection())